<template>
<l-layout class="l-tab-page" v-if="!lr_loadPage" >
    <template #left>
        <l-panel style="padding-right:0;" class="l-panel-overflow">
            <template #title>
                {{$t('分类')}}
                <div class="tree-setting-btn">
                    <el-tooltip effect="dark" :content="$t('设置')" placement="top">
                        <el-button @click="handleSettingClick" type="text" icon="el-icon-setting"></el-button>
                    </el-tooltip>
                </div>
            </template>
            <el-tree class="learun-tree"  ref="tree" v-loading="treeLoading" node-key="id" :highlight-current="true"  :data="dataItemTree_FormSort"   @node-click="handleNodeClick">
                <span class="lr-tree-node"  slot-scope="{ node }">
                    <i class="el-icon-notebook-2"></i>
                    {{ node.label }}
                </span>
            </el-tree>
        </l-panel>
    </template>

    <l-panel style="padding-left:0;" >
        <template #toolLeft >
            <div class="l-panel--item" >
                <el-input :placeholder="$t('please enter名称')" @keyup.enter.native="hanleSearch"  v-model="keyWord" size="mini" >
                    <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                </el-input>
            </div>
        </template>
        <template #toolRight >
            <l-tool-btns @click="handleAdd()" >
                <l-excel-btns></l-excel-btns>
                <el-button-group
                    ><l-file-import
                    fileType="json"
                    classname="custmerFormSchemeImport"
                    @success="exportSuccess()"
                    ></l-file-import
                ></el-button-group>
            </l-tool-btns>
        </template>
        <l-table 
            :loading="tableLoading"
            :columns="columns" 
            :dataSource="tableData" 
            row-key="f_Id"
            :isPage="true"
            :pageTotal="tableTotal"
            :tablePage.sync="tableCurrentPage"

            @loadPageData="turnTablePage"
             >
            <template v-slot:f_CreateDate="scope" >
                {{lr_dateFormat(scope.row.f_CreateDate)}}
            </template>
            <template v-slot:f_Category="scope" >
                {{lr_dataItemName(lr_dataItem['FormSort'],scope.row.f_Category)}}
            </template>
            <template v-slot:f_FormType="scope" >
                <el-tag v-if="scope.row.f_FormType == 1" size="mini" type="warning">{{$t('视图表单')}}</el-tag>
                <el-tag v-else-if="scope.row.f_FormType == 0" size="mini" type="success">{{$t('常规表单')}}</el-tag>
                <el-tag v-else size="mini" type="success">{{$t('自动建表')}}</el-tag>
            </template>
            <template v-slot:f_EnabledMark="scope" >
                <el-tag v-if="scope.row.f_Type != 1" size="mini" >{{$t('草稿')}}</el-tag>
                <el-switch v-else
                    :active-value="1"
                    :inactive-value="0"
                    v-model="scope.row.f_EnabledMark"
                    @change="handleEnableChange(scope.row)"
                    >
                </el-switch>
            </template>
            <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
        </l-table>
    </l-panel>
    <l-fullscreen-dialog
        :title="$t(`表单设计`)"
        :headerMidWidth="400"
        :visible.sync="formVisible"

        :isStep="true"
        :steps="['基本配置','表单设计']"
        :stepActive.sync="stepActive"
        :validateSteps="handleValidateSteps"

        @ok="handleSave"
        @closed="handleClosed"
        @opened="handleOpened"

        ref="formDialog"
        >
        <template #headerRight >
            <el-button @click="handleSaveDraft()" type="warning" size="mini" >{{$t('暂存')}}</el-button>
        </template>
        <formDesign-form ref="form" :stepActive="stepActive" :isDisabled="formEdit"> 
        </formDesign-form>
    </l-fullscreen-dialog>

    <l-drawer 
        :title="$t('分类管理')"
        :visible.sync="classifysVisible"
        :showOk="false"
        :showClose="false"
        size="800px"
        >
        <l-dataitem-index classifyCode="FormSort"></l-dataitem-index>
    </l-drawer>

    <l-dialog
        :title="`${$t('表单Preview')}-${$t(previewTitle)}`"
        :visible.sync="previewVisible"
        :height="600"
        width="800px"
        :hasBtns="false"

        @opened="handlePreviewOpened"
        @closed="handlePreviewClosed"
        >
        <preview ref="preview" ></preview>

    </l-dialog>

    <l-drawer 
        :title="`${$t('历史记录')}-${$t(historyTitle)}`"
        :visible.sync="historyVisible"
        :showOk="false"
        :showClose="false"
        size="640px"

        @opened="HistoryOpened"
    >
        <history ref="HistoryForm" :schemeInfoId="schemeInfoId" :schemeId="schemeId" :updateSchemeId="updateSchemeId" ></history>
    </l-drawer>
    <l-dialog
        :title="$t('表结构配置')"
        :visible.sync="tableStructureVisible"
        :height="700"
        :width="900"
        ref="formTableStructure"
        @opened="handleTableStructureOpened"
        @closed="handleTableStructureClosed"
        @ok="handleTableStructureOk"
        >
        <table-structure ref="tableStructure" ></table-structure>

    </l-dialog>
</l-layout>
</template>

<script>
const api = window.$api.custmerForm.scheme

import formDesignForm from './form'
import preview from './preview'
import history from './history'
import tableStructure from './tableStructureForm'
export default {
    components: {
        formDesignForm,
        preview,
        history,
        tableStructure
    },
    data () {
        return {
            lr_isPage:true,
            // 设计表单
            stepActive: 0,
            stepPrevBtn:true,
            stepNextBtn:false,
            stepSaveBtn:true,
            formVisible:false,

            // 左侧树形
            treeLoading:false,
            treeCategory:'',
            classifysVisible:false,


            // 表格
            columns: [
                {label:'名称',prop:'f_Name',minWidth:'150'},
                {label:'分类',prop:'f_Category',width:'140',align:'center'},
                {label:'类型',prop:'f_FormType',width:'100',align:'center'},
                
                {label:'状态',prop:'f_EnabledMark',width:'64',align:'center'},
                {label:'创建人',prop:'f_CreateUserName',width:'100',align:'center'},
                {label:'创建时间',prop:'f_CreateDate',width:'160'}
            ],
            tableBtns:[
                {prop:'Edit',label:'Edit',width:40},
                {prop:'Delete',label:'Delete',width:40},
                {prop: 'Copy', label: "复制",width:40 },
                {prop: 'Export', label: "导出",width:40 },
                {prop:'Preview',label:'Preview',width:40},
                {prop:'History',label:'历史记录',width:60}
            ],
            tableLoading:false,
            
            tableTotal:0,
            tablePageSize:50,
            tableCurrentPage:1,
            tableData: [],
            keyWord:'',

            formEdit:false,
            formEditRow:null,
            formLoading:false,
            formLoadingText:'',

            // 表单Preview
            previewVisible:false,
            previewTitle:'',
            previewLoading:false,
            
            // 
            historyVisible:false,
            historyTitle:'',
            schemeInfoId:'',
            schemeId:'',

            formCopy:false,//复制操作

            tableStructureVisible: false,
        }
    },
    created () {
        this.lr_loadDataItem('FormSort')
        this.loadTablePageData()
    },
    mounted () {
    },
    computed:{
        dataItemTree_FormSort(){
            return this.lr_dataItemTree(this.lr_dataItem['FormSort'])
        }
    },
    methods:{
        loadTablePageData(isNotFirst){
            if(!isNotFirst){
                this.tableCurrentPage = 1;
            }
            this.tableLoading = true;
            let queryData = {
                rows:this.tablePageSize,
                page:this.tableCurrentPage,
                sidx:'F_CreateDate DESC',
                category:this.treeCategory,
                keyword:this.keyWord
            }
            api.getPage(queryData).then(res=>{
                const data = this.$deepClone(res.data.data);
                this.tableData = data.rows;
                this.tableTotal = data.records;

                this.tableLoading = false;

            }).catch(()=>{
                this.tableData = [];
                this.tableLoading = false;
            });
        },
        turnTablePage({rows}){
            this.tablePageSize = rows;
            this.loadTablePageData(true);
        },
        hanleSearch(){
            this.loadTablePageData();
        },

        handleSettingClick(){
            this.classifysVisible = true;
        },
        handleNodeClick(node) {
            this.treeCategory = node.value
            this.loadTablePageData(true)
        },

        // 表单部分
        handleAdd(){
            this.formEdit = false;
            this.formCopy = false;
            this.showForm();
        },
        handleEdit($index,row){
            this.formEdit = true
            this.formEditRow = row
            this.formCopy = false;
            this.showForm()
        },
        handleDelete($index,row){
            this.$confirm('This operation will permanently delete the data. Do you want to continue?', 'Tips', {
                confirmButtonText: 'confirm',
                cancelButtonText: 'cancel',
                type: 'warning'
            }).then(() => {
                this.tableData.splice($index,1)
                this.tableTotal--
                api.remove(row.f_Id).then(()=>{
                    this.$message({
                        type: 'success',
                        message: 'Delete  success'
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: 'Delete has been canceled'
                })          
            })
        },
        handleSaveDraft(){
            this.handleSave(this.$refs.formDialog.showLoading,this.$refs.formDialog.hideLoading,true)
        },
        handleSave(showLoading,hideLoading,isDraft,isAutoCreateTable){
            if (this.$refs.form.formData.f_FormType != 2 && !this.$refs.form.dbTableData.length) {
                this.$message({
                    type: 'error',
                    message: '请添加数据库表!'
                });
                return;
            }
            // 判断是否是自动建表，且为保存
            if(this.$refs.form.formData.f_FormType == 2 && !isDraft && !isAutoCreateTable) {
                this.tableStructureVisible = true
                return
            }
            showLoading('saving data...')
            if(!isDraft && !this.$refs.form.validateForm()){
                hideLoading()
                return
            }
            let dataInfo = {}
            if(isAutoCreateTable) {
                dataInfo = this.$refs.tableStructure.getForm()
            if (!dataInfo) {
                hideLoading()
                return
            }

            }
            let postData = this.$refs.form.getForm(isDraft,isAutoCreateTable, dataInfo)
            if(this.formEdit){
                api.update(this.formEditRow.f_Id,postData).then(() =>{
                    this.loadTablePageData(true)
                    this.$message({
                        type: 'success',
                        message: '更新成功!'
                    })
                    if(!isDraft) {
                        this.formVisible = false
                    }
                    if (isAutoCreateTable) {
                        this.tableStructureVisible = false
                    }
                    hideLoading()
                })
                .catch(()=>{
                    hideLoading()
                })
            }
            else{
                api.add(postData).then((res) =>{
                    this.formEditRow = res.data.data
                    this.formEdit = true
                    this.loadTablePageData(true)
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    })
                    if(!isDraft) {
                        this.formVisible = false
                    }
                    if (isAutoCreateTable) {
                        this.tableStructureVisible = false
                    }
                    hideLoading()
                })
                .catch(()=>{
                    hideLoading()
                })
            }
        },
        handleEnableChange(row){
            api.updateState(row.f_Id,row.f_EnabledMark).then(()=> {
                this.$message({
                    type: 'success',
                    message: '更新成功!'
                })
            })
        },
        handlePreview($index,row){
            this.formEditRow = row
            this.previewLoading = true
            this.previewVisible = true
            this.previewTitle = row.f_Name
        },
        async handlePreviewOpened(showLoading,hideLoading){
            showLoading('Loading...')
            const data = await this.$awaitWraper(api.getHistory(this.formEditRow.f_SchemeId))
            data && this.$refs.preview.setForm(data)
            hideLoading()
        },
        handlePreviewClosed(){
            this.$refs.preview.resetForm()
        },
        

        handleHistory($index,row){
            this.formEditRow = row;
            this.historyTitle = row.f_Name;
            this.schemeId = row.f_SchemeId;
            this.schemeInfoId = row.f_Id;
            
            this.historyVisible = true;
        },
        HistoryOpened(){
            this.$refs.HistoryForm.loadTablePageData()
        },
        updateSchemeId(id){
            this.schemeId = id
            this.formEditRow.f_SchemeId = id
        },
        showForm(){
            this.formVisible = true
        },

        handleValidateSteps(){
            return this.$refs.form.validateSteps()
        },
        async handleOpened(showLoading,hideLoading){
            if(this.formEdit||this.formCopy){
                showLoading('Loading data...')
                var res = await this.$refs.form.setForm(this.formEditRow.f_Id,this.formCopy)
                hideLoading()
                if(!res){
                    this.formVisible = false
                }
            }
        },
        handleClosed(){
            this.$refs.form.resetForm()
        },
        //表单设计的复制
        handleCopy($index, row) {
            this.formEdit = false;
            this.formCopy = true;
            this.formEditRow = row;
            this.showForm();
        },
        //表单设计的导出
        handleExport($index, row) {
            this.lr_downTempFile(
                `custmerform/scheme/download/custmerform/${row.f_Id}`,
                `表单设计_${row.f_Name}`,
                "custmerform",
                "json"
            );
        },
        exportSuccess(){
            this.loadTablePageData();
        },
        // exportError(){
        //     console.log();
        //     this.handleLoading.close()
        // },

        handleTableStructureOpened() {
            const mainData = this.$refs.form.mainTableName
            const dataInfo = this.$refs.form.$refs.formDesign.getData()
            this.$refs.tableStructure.setForm(dataInfo, mainData)
        },
        handleTableStructureClosed() {
            this.$refs.tableStructure.resetForm()
        },
        handleTableStructureOk() {
            this.handleSave(this.$refs.formTableStructure.showLoading,this.$refs.formTableStructure.hideLoading,false,true)

        }
    }
}
</script>
